import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:dio/src/response.dart';

import '../../utils/log_utils.dart';
import '../app_config.dart';
import '../events.dart';
import '../service/device_info.dart';

import 'net_config.dart';

final Http http = Http();

class Http extends BaseHttp {

  String contentType = "application/json";

  @override
  void init() {
    options.baseUrl = EnvironmentConst.apiBaseUrl;
    options.headers = {
      HttpHeaders.contentTypeHeader: contentType,
    };
    interceptors.clear();
    interceptors.add(ApiInterceptor());
  }

  //添加了isJsonData字段, contenType格式是否是json格式
  //type 1: 公司内部接口 2: ai系统助手 3: 腾讯一句话识别
  Future<ResponseData> httpRequest(String path, methodType, {data, bool isJsonData = true, int type = 1}) async {
    options.baseUrl = EnvironmentConst.apiBaseUrl;
    if (type == 1) {
      options.baseUrl = EnvironmentConst.apiBaseUrl;
    } else if (type == 2) {
      options.baseUrl = 'http://49.51.107.73:8889/chatgpt';
    } else if (type == 3) {
      options.baseUrl = 'http://asr.tencentcloudapi.com';
      options.headers[HttpHeaders.contentTypeHeader] = "application/json";
      options.headers['X-TC-Version'] = '2019-06-14';
      options.headers['X-TC-Region'] = 'ap-shanghai';
      options.headers['X-TC-Action'] = 'SentenceRecognition';
      options.headers['X-TC-Timestamp'] = 'SentenceRecognition';
      options.headers['Authorization'] = 'TC3-HMAC-SHA256 Credential=null/2023-04-13/cvm/tc3_request, SignedHeaders=content-type;host;x-tc-action, Signature=bbd549ab8dc8747a02d6c44bef72b6de3f9c9f704f9557030cdd1c99a02587f8';
    }

    if (type == 1 || type == 2) {
      if (isJsonData) {
        options.headers[HttpHeaders.contentTypeHeader] = "application/json";
      } else {
        options.headers[HttpHeaders.contentTypeHeader] = "application/x-www-form-urlencoded";
      }
    }
    try {
      var res;
      switch (methodType) {
        case MethodType.POST:
          res = await http
              .post(path, data: data);
          break;
        case MethodType.GET:
          res = await http
              .get(path, queryParameters: data);
          break;
        case MethodType.PATCH:
          res = await http
              .patch(path, data: data);
          break;
        case MethodType.DELETE:
          res = await http
              .delete(path, data: data);
      }
      return ResponseData.fromJson(res.data);
    } on TimeoutException catch (_) {
      LogUtilTool.println('请求超时,请检查网络 ---- $path');
      return ResponseData.fromJson({"code": 114, "msg": '请求超时,请检查网络'});
    } catch (e) {
      LogUtilTool.println("请求错误3 ------ $e ${http.options.baseUrl}");
      if (e is DioError) {
        if (e.response != null) {
          return ResponseData.fromJson({
            "code": e.response!.statusCode,
            "msg": e.message,
            'data': ''
          });
        }
        return ResponseData.fromJson(
            {"code": 113, "msg": '网络异常，请检查网络后重试', 'data': ''});
      }
      return ResponseData.fromJson(
          {"code": 113, "msg": '网络异常，请检查网络后重试', 'data': ''});
    }
  }

}

class HttpUpFile extends BaseHttp {
  String contenType;

  HttpUpFile({
    Key? key,
    this.contenType = "multipart/from-data",
  }) : super(key: key);


  @override
  void init() {
    options.baseUrl = EnvironmentConst.apiBaseUrl;
    options.headers = {
      HttpHeaders.contentTypeHeader: contenType,
    };
    interceptors.add(ApiInterceptor());
  }

}

class ApiInterceptor extends InterceptorsWrapper {
  //手机系统时间与服务器时间偏移量（用于同步服务器时间）
  static int systemTimeOffset = 0;

  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) async {

    options.headers['channelPackage'] = channelPackage;
    options.headers['platform'] = GetPlatform.isAndroid ? '1' : '2';
    // if ((options.headers['version'] ?? '').isEmpty) {
    //   var appVersion = await PlatformUtils.getAppVersion();
    //   options.headers['version'] = appVersion;
    // }
    options.headers['deviceId'] = DeviceInfo.to.divceID;

    LogUtilTool.println('--api-request-->url--> ${options.baseUrl}${options.path}');
    LogUtilTool.println('--api-request-->header--> ${options.headers}');
    LogUtilTool.println('--api-request-->data--> ${options.data}');
    LogUtilTool.println(
        '--api-request-->queryParameters--> ${options.queryParameters}');
    return handler.next(options);
  }

  @override
  onResponse(Response response, ResponseInterceptorHandler handler) async {
    LogUtilTool.println('onResponse ${response.data.toString()}');
    ResponseData respData = ResponseData.fromJson(response.data);
    // if (response.data['code'] == null) {
    //   respData = ResponseData.fromJson({'code' : 200, 'data' : response.data['resp']['choices'][0]['message']['content']});
    //   response.data = respData.toJson();
    //   return handler.next(response);
    //   print('respData = ${respData.data}');
    // } else {
    //   respData = ResponseData.fromJson(response.data);
    // }

    // try {
    //   var date = response.headers['date']; //[Thu, 28 Apr 2022 06:06:40 GMT]
    //   DateTime parsedDate = HttpDate.parse(date.toString().substring(1, date.toString().length - 1));
    //   //服务器响应时间(该时间只精确到秒)
    //   int netTime = parsedDate.millisecondsSinceEpoch;
    //   //接口请求手机系统时间戳
    //   int nowTime1 = response.requestOptions.headers['timestamp'];
    //   //接口响应手机系统时间戳
    //   int nowTime2 = DateTime.now().millisecondsSinceEpoch;
    //   //请求单向耗时约为
    //   //时间差 = 请求时间 + 服务器耗时 + 响应时间  此处简单的除2并不精确
    //   int takeUpTime = (nowTime2 - nowTime1) ~/ 2;
    //   //当前服务器时间
    //   int nowNetTime = netTime + takeUpTime;
    //   //手机时间与服务器时间偏移量（用于处理修改手机系统时间问题）
    //   systemTimeOffset = nowTime2 - nowNetTime;
    //
    // } catch (e) {
    //   LogUtilTool.println('e =====$e');
    // }

    LogUtilTool.println(
        '--api-response-->respData.data-->${response.requestOptions.baseUrl}${response.requestOptions.path}   ${LogUtilTool.encoder.convert(response.data)}');
    if (respData.success) {
      return handler.next(response);
    } else {
      //如果接口出错了，没有解析data错误异常数据
        if (respData.code == 100010) {
          //登录失效
          // MySettingsLogic().logout();
          eventBus.fire(LogoutEvent(refreshPage: true));
        }

        LogUtilTool.println(
            '请求失败----${response.statusCode} ${response.statusCode} ${response.statusMessage}');
        return handler.next(response);
      }
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    LogUtilTool.println(
        '接口请求失败  ---- ${err.message} path: ${err.requestOptions.path}  header:${err.requestOptions.headers}');
    super.onError(err, handler);
  }
}

class ResponseData extends BaseResponseData {
  @override
  bool get success => 200 == code;

  ResponseData();

  ResponseData.fromJson(Map<dynamic, dynamic> json) {
    if (json['code'] is int) {
      code = json['code'];
    } else {
      code = int.parse(json['code']);
    }
    msg = json['msg'];
    data = json['data'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> map = <String, dynamic>{};
    map['code'] = code;
    map['msg'] = msg;
    map['data'] = data;
    return map;
  }
}